# -*- coding: utf-8 -*-
"""订单确认与提交页面对象。

封装了：
1. 收货信息检查
2. 提交订单
3. 成功弹窗文案获取
"""

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from .base import BasePage
from common.log import log


class OrderPage(BasePage):
    """提交订单页面对象"""

    # -------- 元素定位 --------
    ADDRESS_TEXT = (By.CSS_SELECTOR, ".user_info_check")  # 当前地址 / 收件人 / 电话
    PAYMENT_COD = (By.CSS_SELECTOR, "label.cash")  # 默认选中货到付款，暂留
    SUBMIT_BTN = (By.ID, "order_btn")  # 提交订单按钮
    SUCCESS_POPUP = (By.CSS_SELECTOR, ".popup_con .popup p")  # 成功提示弹窗内文字

    # -------- 页面操作封装 --------
    def is_address_filled(self) -> bool:
        """检查页面收货地址是否已填写"""
        # 页面存在多处 .user_info_check，任取其一判断文本是否为空
        elements = self.driver.find_elements(*self.ADDRESS_TEXT)
        for el in elements:
            if el.text.strip():
                return True
        return False

    def submit_order(self):
        """点击“提交订单”按钮"""
        log.info("点击提交订单按钮")
        self.click(self.SUBMIT_BTN)

    def success_message(self, timeout: int = 5) -> str:
        """等待并返回成功提示文字。如果未出现则返回空串"""
        try:
            WebDriverWait(self.driver, timeout).until(
                EC.visibility_of_element_located(self.SUCCESS_POPUP)
            )
            text = self.text_of(self.SUCCESS_POPUP)
            log.debug(f"订单提交结果弹窗文本: {text}")
            return text
        except Exception as e:
            log.error(f"等待订单成功弹窗失败: {e}")
            return "" 